import TileLayer from 'ol/layer/Tile'
import TileArcGISRest from 'ol/source/TileArcGISRest'
import XYZ from 'ol/source/XYZ'
import { fromLonLat, get } from 'ol/proj'

class TileArcGIS {
  addTile (opt) {
    var projection = get('EPSG:3857')
    const esriTileUrlFunction = tileCoord => {
      var tileurl = opt.url + 'L{z}/R{y}/C{x}' + '.png'
      if (!tileCoord) {
        return undefined
      } else {
        var z = tileCoord[0]
        if (z < 10) {
          z = '0' + z
        }
        var tempX = '00000000' + (tileCoord[1]).toString(16)
        var tempY = '00000000' + (tileCoord[2]).toString(16)
        // return this.urls[0].replace('{x}', tempX.substring(tempX.length - 8)).replace('{y}', tempY.substring(tempY.length - 8)).replace('{z}', z)
        return tileurl.replace('{x}', tempX.substring(tempX.length - 8)).replace('{y}', tempY.substring(tempY.length - 8)).replace('{z}', z)
      }
    }

    const source = new XYZ({
      projection: projection,
      tileUrlFunction: esriTileUrlFunction,
      crossOrigin: '*'
    })
    const layer = new TileLayer({
      source: source
    })
    return layer
  }
}

export default TileArcGIS
